package com.jzoffer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 将一个字符串转换成一个整数，要求不能使用字符串转换整数的库函数。
// 数值为0或者字符串不是一个合法的数值则返回0
public class ConvertStrToInt {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        int res = strToInt(str);
        System.out.println(res);
        br.close();
    }

    public static int strToInt(String str){
        if(str == null || str.length() < 1){
            return 0;
        }
        boolean isNegative = false;
        int start = 0;
        int res = 0;
        if(str.charAt(0) == '+'){
            start = 1;
        }
        if(str.charAt(0) == '-'){
            start = 1;
            isNegative = true;
        }
        for(int i = start;i < str.length();i++){
            char tmp = str.charAt(i);
            if(tmp >= '0' && tmp <= '9'){
                res = res * 10 + (tmp - '0');
                if(isNegative && res < Integer.MIN_VALUE){
                    throw new RuntimeException("下溢出");
                }
                if(!isNegative && res > Integer.MAX_VALUE){
                    throw new RuntimeException("上溢出");
                }
            }else{
                return 0;
            }
        }

        return isNegative ? -1 * res:res;
    }


}
